import {queryParams} from '@/script/tools.js'
export let getUrlCode = function (name) { 
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null 
}

export function isWechat(){ 
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"; 
}

// 删除url中某个参数,并跳转
export function funcUrlDel(nameArr){
 //  let loca = window.location, url = ''
 //  let baseUrl = loca.origin + loca.pathname;
 //  let query = loca.search.substr(1);
 //  let obj = {}
 //  let arr = query.split("&");
 //  for (let i = 0; i < arr.length; i++) {
 //    arr[i] = arr[i].split("=");
 //    obj[arr[i][0]] = arr[i][1];
 //  };
 //  nameArr.forEach(name => {    
 //    if (query.indexOf(name)>-1) {
 //      delete obj[name];
 //    };
 //  })
	// url = baseUrl + queryParams(obj);
 //  return url
 let url = window.location.href;
 let parsedUrl = new URL(url);
 let params = new URLSearchParams(parsedUrl.search);
	nameArr.forEach(name => {
		params.delete(name);
	})
	let updatedUrl = parsedUrl.origin + parsedUrl.pathname
	
	if (params.toString()) {
	    updatedUrl += '?' + params.toString();
	}
	return updatedUrl
}

export const replaceWxUrl = () => {
	let path = funcUrlDel(['code', 'state'])
	window.history.replaceState({
		path
	}, '', path);
	return path
}

export let getWxCode = function (callbackUrl) { 
	if(isWechat()) {
		let query = {
			appid: 'wxa60cb5358289e03b',
			redirect_uri: encodeURIComponent(callbackUrl),
			response_type: 'code',
			scope: 'snsapi_userinfo',
			state: 1,
		}
	 let code = getUrlCode('code')
	 if (code === null || code === '') { 
		 let url = `https://open.weixin.qq.com/connect/oauth2/authorize${queryParams(query)}#wechat_redirect`
		 window.location.href = url		 
		}else{
			// let path = funcUrlDel(['code', 'state'])
			// window.history.replaceState({
			// 	path: path
			// }, '', url);
		}
	}
}
